﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using GrpcClient;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

namespace AspNetCoreGrpcClient.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AspNetCoreGrpcClientController : ControllerBase
    {
        private readonly GrpcDemo.GrpcDemoClient _client;

        Random random = new Random();
        public AspNetCoreGrpcClientController(GrpcDemo.GrpcDemoClient client)
        {
            _client = client;
        }
        [HttpGet]
        public async Task<IActionResult> GetInfo()
        {
            try
            {
                //await
                var res = _client.GetMessgae(new Request { Info = "1" });



                //  Byte[] str = res.Arrays.ToByteArray();

                // var obj = Bytes2Object(str);
                //  Console.WriteLine("返回数据：" + res.Arrays);

                /*
                 
                {
 {9, 1.02f, 2, 3,9, 1.02f, 2, 3} ,   
                { 4, 5, 6, 7f,9, 1.02f, 2, 3} ,   
 { 8, 9, 10, 11,9, 1.02f, 2, 3}   
            };

            */


                float[,] a = new float[200, 8];

                for (int i = 0; i < 200; i++)
                {
                    for (int j = 0; j < 8; j++)
                    {
                        a[i, j] = random.Next(1, 20) / 10;
                    }
                }

                var req = ObjectToBytes(a);
                //  res.Arrays

                //  var res2 = await _client.SetUserInfoAsync(new SetRequest { Arrays = Google.Protobuf.ByteString.CopyFrom(req) });


                var request = new SetRequest { };//Arrays = Google.Protobuf.ByteString.CopyFrom(req)
                //for (int i = 0; i < 10; i++)
                //{
                //       request.ListArrays.Add(new DataList { });
                //  // request.Arrays = request.Arrays + i; //Google.Protobuf.ByteString.CopyFromUtf8(  "" + i);
                //}


                for (int i = 0; i < a.GetLength(0); i++)
                {
                    var list = new DataList { };
                    for (int j = 0; j < a.GetLength(1); j++)
                    {
                        Console.WriteLine(a[i, j]);
                        list.Arrays.Add(a[i, j]);
                    }
                    request.ListArrays.Add(list);
                }



                // request.Arrays = request.Arrays + "发送数据";
                var res2 = await _client.SetUserInfoAsync(request);

                return new JsonResult(res2);
            }
            catch (Exception ee)
            {

                return new JsonResult(ee);
            }


        }

        /// <summary> 
        /// 将一个object对象序列化，返回一个byte[]         
        /// </summary> 
        /// <param name="obj">能序列化的对象</param>         
        /// <returns></returns> 
        public static byte[] ObjectToBytes(object obj)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, obj); return ms.GetBuffer();
            }
        }

        /// <summary>
        /// 将byte数组转换成对象
        /// </summary>
        /// <param name="buff">被转换byte数组</param>
        /// <returns>转换完成后的对象</returns>
        public static object Bytes2Object(byte[] buff)
        {
            object obj;
            using (MemoryStream ms = new MemoryStream(buff))
            {
                IFormatter iFormatter = new BinaryFormatter();
                obj = iFormatter.Deserialize(ms);
            }
            return obj;
        }




        [HttpPost(nameof(GetUser))]
        public async Task<IActionResult> GetUser()
        {
            //  var res = await _client.GetMessgaeAsync(new Request { Info = "1" });
            //  var res = await _client.GetUserInfoAsync(new Request { Info =DateTime.Now.ToString()});
            return new JsonResult("22");
        }
    }
}
